<?php
$result = [
    'status' => 0,
    'data' => null,
    'message' => '未知错误'
];

include_once '../mysql/sql.php';
include_once '../mysql/sql-feedback.php';

if (isset($sql) && $sql) {
    $params = [];

    $params['username'] = isset($_POST['username']) ? $_POST['username'] : null;
    $params['password'] = isset($_POST['password']) ? $_POST['password'] : null;
    
    if (!$params['username']) {
        $result['status'] = 0;
        $result['data'] = false;
        $result['message'] = '用户名不能为空';
    }
    else if (!$params['password']) {
        $result['status'] = 0;
        $result['data'] = false;
        $result['message'] = '密码不能为空';
    }
    else {
        $login = login($mysql, $params);
        if ($login) {
            if ($login[0]['password'] === $params['password']) {
                session_start();

                $result['status'] = 1;
                $result['data'] = $params['username'];

                if (isset($_SESSION['userid']) && ($_SESSION['userid'] === $login[0]['id'])) {
                    $result['message'] = '已登入, 请勿重复登入';
                }
                else {
                    $_SESSION['userid'] = $login[0]['id'];
                    $result['message'] = '登入成功';
                };
            }
            else {
                $result['status'] = 0;
                $result['data'] = $params['username'];
                $result['message'] = '密码错误';
            };
        }
        else {
            $result['status'] = 0;
            $result['data'] = $params['username'];
            $result['message'] = '用户未注册';
        };
    };

    // 关闭连接
    $mysql->close();
}
else {
    $result['message'] = '数据库连接错误';
};

echo json_encode($result);

// 登入
function login(&$mysql,$params) {
$statement = <<< EOT
select * from users
where username = '{$params["username"]}' or email = '{$params["username"]}' or phone = '{$params["username"]}'
EOT;
    //echo '<hr />', $statement, '<hr />';
    return sql_feedback($statement, $mysql);
};
?>